﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using ProjectBilling.DataAccess;

namespace ProjectBilling.UI.RAD
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            System.Windows.Data.CollectionViewSource projectViewSource 
                = ((System.Windows.Data.CollectionViewSource)
                (FindResource("projectViewSource")));
            // Load data by setting the 
            // CollectionViewSource.Source property:
            projectViewSource.Source = new DataServiceStub().GetProjects();
        }

private void nameComboBox_SelectionChanged(object sender, 
    SelectionChangedEventArgs e)
{
    ComboBox comboBox = sender as ComboBox;

    // If there is a selected item
    if (comboBox != null && comboBox.SelectedIndex > -1)
    {
        Project selectedProject 
            = comboBox.SelectedItem as Project;

        SetEstimateColor(selectedProject);
        updateButton.IsEnabled = true;
    }
    else
    {
        nameTextBox.IsEnabled = false;
        estimateTextBox.IsEnabled = false;
        actualTextBox.IsEnabled = false;
        updateButton.IsEnabled = false;
    }
}

private void SetEstimateColor(Project selectedProject)
{
    if (selectedProject.Actual == 0)
    {
        estimateTextBox.Foreground
            = Brushes.Black;
    }
    else if (selectedProject.Actual
        <= selectedProject.Estimate)
    {
        estimateTextBox.Foreground
            = Brushes.Green;
    }
    else
    {
        estimateTextBox.Foreground
            = Brushes.Red;
    }
}

private void updateButton_Click(object sender, 
    RoutedEventArgs e)
{
    Project selectedProject
        = nameComboBox.SelectedItem
        as Project;
    if (selectedProject != null)
    {
        selectedProject.Name = nameTextBox.Text;
        selectedProject.Estimate =
            double.Parse(estimateTextBox.Text);
        if (!string.IsNullOrEmpty(
            actualTextBox.Text))
        {
            selectedProject.Actual
                = double.Parse(
                    actualTextBox.Text);
        }
        SetEstimateColor(selectedProject);
    }
}
    }
}
